<!DOCTYPE html>
<html>

	<head>
		<meta charset="utf-8">
		<title>view/workArea/parts/applyParts</title>
		<meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=1,user-scalable=no">
		<meta name="apple-mobile-web-app-capable" content="yes">
		<meta name="apple-mobile-web-app-status-bar-style" content="black">

		<link rel="stylesheet" href="../../../css/mui.min.css">
		<link rel="stylesheet" href="../../../css/global.css">
		<link rel="stylesheet" href="../../../css/style.css">
		<style>
			.mui-radio input[type=radio]{
				left: 0;
				top: 12px;
			}
			.mui-radio input[type=radio]:before{
				font-size: 18px;
			}
			.mui-radio.mui-left label{
				padding-left: 40px;
				line-height: 50px;
			}
			.mui-checkbox, .mui-radio{
				margin-left: -1.125rem;
				float: right;
			}
			
			.sel{
				font-size: 12px;
				margin-left: 10px;
				color: #ffffff;
				background: #ea1e1a;
				height: 20px;
				line-height: 12px !important;
				margin-top: 15px;
				border-radius: 5px;
				padding: 5px;
			}
			.selectxx{
				position: absolute;
				right: 10px;
			}
		</style>
	</head>

	<body>
		<header class="mui-bar mui-bar-nav">
			<a class="mui-action-back mui-icon mui-icon-left-nav mui-pull-left"></a>
			<h1 id="title" class="mui-title">备件申请</h1>
		</header>
		<div class="mui-content">
			<div class="details_con" id="form_info">
				<div class="clum autoHeight">
					<!-- autoHeight -->
					<div class="r_radio" id="Type" style="width: 100%;">
						<!--  style="margin-left: 60px;" -->
						<div class="mui-radio mui-left" style="float: left;">
							<input name="Type" value="1" id="rodio_1" type="radio" class="rds applytype" onchange="changeType(1)" checked="checked"/>
							<label>服务通知</label>
						</div>
						<div class="mui-radio mui-left" style="float: left;">
							<input name="Type" value="2" id="rodio_2" type="radio" class="rds applytype" onchange="changeType(2)" />
							<label>无服务通知</label>
						</div>
						<div class=" mui-radio mui-left" style="float: left;">
							<input name="Type" value="3" id="rodio_3" type="radio" class="rds applytype" onchange="changeType(3)" />
							<label>返库</label>
						</div>
					</div>
				</div>
				<div class="clum" id="FWDH">
					<span class="name">服务编号<em class="t_red">*</em></span>
					<span class="sel selectxx" id="selectDetailsBtn">查询</span>		
					<input type="text" class="d_ipt" id="service_no" name="service_no" required="required" placeholder="请输入服务编号" />
				</div>
				<div class="clum">
					<span class="name">是否加急<em class="t_red">*</em></span>
					<div class="r_radio" id="IsUrgent" style="margin-left: 60px;">
						<div class="mui-radio mui-left">
							<input name="IsUrgent" value="0" type="radio" class="rds" checked="checked" />
							<label>否</label>
						</div>
						<div class="mui-radio mui-left">
							<input name="IsUrgent" value="1" type="radio" class="rds" />
							<label>是</label>
						</div>
					</div>
				</div>
				<div class="clum">
					<span class="name">非工作时间紧急发货<em class="t_red">*</em></span>
					<div class="r_radio" id="Emergency" style="margin-left: 60px;">
						<div class="mui-radio mui-left">
							<input name="Emergency" id="Emergency_0" value="0" onchange="chengeEmergency(0)" type="radio" class="rds" checked="checked" />
							<label>否</label>
						</div>
						<div class="mui-radio mui-left">
							<input name="Emergency" id="Emergency_1" value="1" onchange="chengeEmergency(1)" type="radio" class="rds" disabled="disabled" />
							<label>是</label>
						</div>
					</div>
				</div>
				<div class="clum">
					<span class="name">是否允许部分发货<em class="t_red">*</em></span>
					<div class="r_radio" id="IsPartShip" style="margin-left: 60px;">
						<div class="mui-radio mui-left">
							<input name="IsPartShip" value="0" type="radio" class="rds" checked="checked" />
							<label>否</label>
						</div>
						<div class="mui-radio mui-left">
							<input name="IsPartShip" value="1" type="radio" class="rds" />
							<label>是</label>
						</div>
					</div>
				</div>
				<div class="clum">
					<span class="name">仪器型号</span>
					<input type="text" class="d_ipt" id="model" name="model" placeholder="请输入仪器型号" />
				</div>
				<div class="clum">
					<span class="name">序列号</span>
					<input type="text" class="d_ipt" id="serialno" name="serialno" placeholder="请输入序列号" />
				</div>
				<div class="clum">
					<span class="name">仪器SO#</span>
					<input type="text" class="d_ipt" id="Sono" name="Sono" placeholder="请输入仪器SO" />
				</div>
				<div class="clum">
					<span class="name">用户名称</span>
					<input type="text" class="d_ipt" id="CustName" name="CustName" placeholder="请输入用户名称" />
				</div>
				<div class="clum">
					<span class="name">受理人</span>
					<input type="hidden" class="hidden" id="Csrcode" name="Csrcode" />
					<input type="text" class="d_ipt" id="Csrname" name="Csrname" disabled="disabled" />
				</div>
			</div>
			<div class="btn_box">
				<span class="fl" id="applyPartsList">备件列表</span>
				<span class="fr red" id="applyPartsAdd">添加备件</span>
			</div>
			<div style="height: 50px;"></div>
			<div class="btn_box">
				<span class="fr red one" id="submitBtn">提交</span>
			</div>
			<div style="height: 50px;"></div>
		</div>

		<!-- js代码 start -->

		<!-- 基础js start -->
		<script src="../../../js/mui.min.js"></script>
		<script src="../../../js/utils/h.js"></script>
		<script src="../../../js/constant.js"></script>
		<script src="../../../js/common.js"></script>
		<script src="../../../js/utils/base64.js"></script>
		<script src="../../../js/utils/md5.js"></script>
		<script src="../../../js/utils/sortMap.js"></script>
		<script src="../../../js/utils/http.js"></script>
		<script src="../../../js/app.js"></script>
		<!-- 基础js end -->

		<script type="text/javascript" charset="utf-8">
			var applyPartsKey = "FSE_ITEM_KEY_APPLY_PARTS";
			var emergencyValue = 0; //当前页紧急发货默认值
			var ServiceNoticeId;
			var khInfo = {};
			var data1=[{"text":"保外借用","value":"1"},{"text":"保内借用","value":"2"},{"text":"服务合同","value":"4"}];
			var data2=[{"text":"个人维修工具","value":"6"},{"text":"备件库存","value":"7"},{"text":"耗材销售","value":"8"}];
			var data3=[{"text":"返库维修","value":"5"}];
			
			var loadingNum = 0;
			var loadingNo = 1;
			(function($, doc) {

				// h("#rodio_1").attr("checked","checked");
				// changeType(1)
				$.init();
				$.back = function(event) {
					h.removeItem(applyPartsKey);
					plus.webview.currentWebview().close(); //退出申请也时，清空缓存
				};
				$.plusReady(function() {
					// 从上一个页面取值
					var self = plus.webview.currentWebview();
					var serviceNo = self.serviceNo; //推荐备件来的会传入serviceNo
					ServiceNoticeId = self.ServiceNoticeId;
					if (serviceNo) {

						h("#service_no").val(serviceNo);
						h("#rodio_2").attr("disabled","disabled");
						h("#rodio_3").attr("disabled","disabled");
						selectByserviceNo();
					}
					
					// 检验工作日
					checkTodayIsOnjobInfo();
					
					if(ServiceNoticeId){
						loadingNo = 2;
						getDetails();
					}

					// 借货受理人
					var csrcode = app.getUser().csrcode;
					h("#Csrcode").val(csrcode);
					var csrname = app.getUser().csrname;
					h("#Csrname").val(csrname);

					// 添加备件
					h("#applyPartsAdd").tap(function() {
						var Type = "";
						var rdsObj1 = document.getElementsByName("Type");
						for (i = 0; i < rdsObj1.length; i++) {
							if (rdsObj1[i].checked) {
								Type = rdsObj1[i].value;
							}
						}
						if (Type == "") {
							app.toast("请选择借货类型")
							return false;
						}
						if (Type == 1 && emptyStr(khInfo.CustName) == "") {
							app.toast("请查询有效服务编号")
							return false;
						}
						
						//非工作时间紧急发货
						khInfo["emergencyValue"] = emergencyValue;
						
						app.jumpTo("applyPartsAdd.html", "view/workArea/parts/applyPartsAdd", {
							"Type" : Type,
							"khInfo" : khInfo
						});
					});

					// 备件列表
					h("#applyPartsList").tap(function() {
						var Type = "";
						var rdsObj1 = document.getElementsByName("Type");
						for (i = 0; i < rdsObj1.length; i++) {
							if (rdsObj1[i].checked) {
								Type = rdsObj1[i].value;
							}
						}
						//非工作时间紧急发货
						khInfo["emergencyValue"] = emergencyValue;
						// if (!h.getItem(applyPartsKey) || h.getItem(applyPartsKey).trim() == "[]") {
						// 	app.toast("请添加备件")
						// 	return false
						// }
						
						// 缓存更新  追加默认数据进入
						
						var items = JSON.parse(h.getItem(applyPartsKey));
						var formObj = {
							"Part_id": "",
							"Remarks": "",
							"Use_type": "",
							"CustName": "",
							"Province": "",
							"City": "",
							"Area": "",
							"shipaddress": "",
							"postcode": "",
							"contactor": "",
							"telephone": "",
							"Mobile": "",
							"Type": Type,
							"userTypeSel": "",
							"showCityPicker3": khInfo.Province + " " + khInfo.City
						}
						if(items && items.length > 0){
							for(var i = 0; i < items.length; i++){
								if(!items[i].userTypeSel){
									items[i] = Object.assign(formObj,khInfo,items[i]);
									items[i].postcode = khInfo.postCode;
									if(khInfo.isWarranty){
										var selectJson = data1.find(function(e){
											return e.text.indexOf(khInfo.isWarranty) !== -1
										})
										items[i].userTypeSel = selectJson.text
										items[i].Use_type = selectJson.value
									}else{
										items[i].userTypeSel = ""
									}
								}
							}
							h.setItem(applyPartsKey, JSON.stringify(items));
						}
						app.jumpTo("applyPartsList.html", "view/workArea/parts/applyPartsList", {
							"khInfo" : khInfo,
							"Type": Type,
						});
					});
					
					// 提交方法
					var dosubmit = function() {
						var formObj = {}; //POST参数对象
						var subFlag = true;
						mui("#form_info input").each(function(index, item) {
							var value = item.value;
							var name = item.getAttribute("id");
							var required = item.getAttribute("required");
							if (required && !value) {
								subFlag = false;
								app.toast(item.getAttribute("placeholder"));
								return false;
							}
							formObj[name] = value; //参数赋值
						});
						
						// 单选按钮校验——类型
						var rdsObj1 = document.getElementsByName("Type");
						var Type = "";
						for (i = 0; i < rdsObj1.length; i++) {
							if (rdsObj1[i].checked) {
								Type = rdsObj1[i].value;
							}
						}
						formObj["Type"] = Type;
						
						// 单选按钮校验——是否加急
						var rdsObj2 = document.getElementsByName("IsUrgent");
						var IsUrgent = "";
						for (i = 0; i < rdsObj2.length; i++) {
							if (rdsObj2[i].checked) {
								IsUrgent = rdsObj2[i].value;
							}
						}
						formObj["IsUrgent"] = IsUrgent;
						
						// 单选按钮校验——非工作时间紧急发货
						var rdsObj4 = document.getElementsByName("Emergency");
						var Emergency = "";
						for (i = 0; i < rdsObj4.length; i++) {
							if (rdsObj4[i].checked) {
								Emergency = rdsObj4[i].value;
							}
						}
						formObj["Emergency"] = Emergency;
						
						// 单选按钮校验——是否部分发货
						var rdsObj3 = document.getElementsByName("IsPartShip");
						var IsPartShip = "";
						for (i = 0; i < rdsObj3.length; i++) {
							if (rdsObj3[i].checked) {
								IsPartShip = rdsObj3[i].value;
							}
						}
						formObj["IsPartShip"] = IsPartShip;
						
						if (subFlag) {
							// 工程师ID
							var enginner_id = app.getUser().enginnerId;
							formObj["enginner_id"] = enginner_id;
							// var itemsArr = new Array();
							// var items = h.getItem(applyPartsKey);
							// if (items) {
							// 	itemsArr = JSON.parse(items);
							// }
							// formObj["Part_info"] = itemsArr;
							// console.log(JSON.stringify(formObj));
							if (!h.getItem(applyPartsKey) || h.getItem(applyPartsKey).trim() == "[]") {
								app.toast("请添加备件")
								return false
							}
						
							var param = {
								"spareParts": encodeURI(JSON.stringify(formObj)),
								"partInfo": encodeURI(h.getItem(applyPartsKey))
							};
							
							// app.showWaiting('加载中...');
							// 提交数据
							ajaxPost(BASE_URL + "cc/spareParts/partBorrowApply", param, function(data) {
								app.closeWaiting()
								// console.log(JSON.stringify(data));
								if (data.code == 200) {
									//保存成功
									app.toast("保存成功");
									$.back();
								} else {
									//保存失败
									var dataObj = JSON.parse(data.data);
									app.toast(dataObj.message);
								}
							}, function(errorMsg) {
								app.closeWaiting()
								console.log(JSON.stringify(errorMsg))
							});
						}
					}

					// 准备提交
					h("#submitBtn").tap(function() {
						// cc接口要求提交前也要校验
						if (emergencyValue == 1) {
							// 校验是否紧急时间
							ajaxGetJson(BASE_URL + 'cc/spareParts/checkTodayIsOnjobInfo', {
							}, function(data) {
								if (data) {
									var dataObj = JSON.parse(data);
									if (dataObj.status) {//返回成功
										if (dataObj.record[0].IsOnjob == 1) {
											// 紧急时段
											h("#Emergency_1").attr("disabled", "disabled");
											h("#Emergency_1").removeAttr("checked");
											app.toast("当前非紧急发货时段，不可选择非工作时间紧急发货")
											return false;
										} else {
											// 非紧急时段
											h("#Emergency_1").removeAttr("disabled");
										}
									}
								}
							});
						} else if (emergencyValue == 0) {
							
							// 缓存备件
							var items = h.getItem(applyPartsKey);
							var	itemsArr = JSON.parse(items);
							if (items && itemsArr.length > 0) {
								var flag = 1;
								for(var i = 0; i<itemsArr.length; i++){
									var info = itemsArr[i];
									var Use_type = info.Use_type;
									if (Use_type == 9) {
										app.toast("备件用途不可选择紧急借货")
										flag = 0;
										return false;
									}
								}
								if (flag) {
									dosubmit();
								}
							} else {
								app.toast("请添加备件")
							}
						}
					});

					// 查询详情
					h("#selectDetailsBtn").tap(function() {
						h("#rodio_1").attr("checked","checked");
						h("#rodio_2").attr("disabled","disabled");
						h("#rodio_3").attr("disabled","disabled");
						selectByserviceNo();
					});
				});
			}(mui, document));
			
			// 清空（未使用）
			function cleanForm(formId) {
				mui("#"+ formId +" input, #"+ formId +" textarea").each(function(index, item) {
					item.value = "";
				});
			}
			
			// 清空输入框
			function cleanInput() {
				h("#model").val("");
				h("#serialno").val("");
				h("#Sono").val("");
				h("#CustName").val("");
				
				khInfo = {};
			}

			// 服务编号显示
			function changeType(value) {
				if (value == 1) {
					h("#rodio_2").attr("disabled","disabled");
					h("#rodio_3").attr("disabled","disabled");
				} else if (value == 2) {
					h("#rodio_1").attr("disabled","disabled");
					h("#rodio_3").attr("disabled","disabled");
				} else {
					h("#rodio_1").attr("disabled","disabled");
					h("#rodio_2").attr("disabled","disabled");
				}
				if (value == 1) {
					h("#FWDH").show();
					// h("#service_no").val("");
					h("#service_no").attr("required","required");
				} else {
					h("#FWDH").hide();
					// h("#service_no").val("");
					h("#service_no").attr("required","");
				}
			}
			
			// 灰常重要的全局变量，用它处理紧急时间校验
			function chengeEmergency(Emergency) {
				emergencyValue = Emergency;
			}
			
			// 经纬度解析省市区
			function getShengshiqv(postx, posty) {
				var url = "https://restapi.amap.com/v3/geocode/regeo?output=JSON&location="+ postx +","+ posty +"&key=4e43ba84d25ec760cd15321e2a48b3a4&radius=1000&extensions=base";
				mui.ajax(url, {
					dataType: 'JSON', //服务器返回json格式数据
					type: 'get', //HTTP请求类型
					async:false,
					timeout: timeout, //超时时间设置为10秒；
					success: function(data) {
						data = JSON.parse(data)
						var province = data.regeocode.addressComponent.province;
						var city = data.regeocode.addressComponent.city;
						var district = data.regeocode.addressComponent.district;
						emptyStr(city) == "" ? province : city;
						resultStr = province + " " + city + " " + district;
						khInfo["shengShiQU"] = resultStr;
						// khInfo["formatted_address"] = data.regeocode.formatted_address;
					},
					error: function(xhr, type, errorThrown) {
						//异常处理；
						// console.log(type);
						// errorHandl(xhr, type, errorThrown, fail);
					}
				});
			}
			
			function selectByserviceNo() {
				var serviceNo = h("#service_no").val();
				if (serviceNo == "") {
					app.toast("请输入服务编号");
					return false;
				}
				// 弹出加载框
				app.showWaiting('加载中...');
				// 清空内容
				cleanInput();
				ajaxPost(BASE_URL + "cc/instrument/getInstrumentByServiceNo", {
					"serviceNo": serviceNo
				}, function(data) {
					loadingNum++;
					if(loadingNum >= loadingNo){
						app.closeWaiting()
					}
					// app.closeWaiting()
					// console.log(JSON.stringify(data))
					if (data.code === 200) {
						if (data.data == null || data.data.length == 0) {
							app.toast("查询无结果");
						} else {
							h("#model").val(data.data[0].instrumentNo);
							h("#serialno").val(data.data[0].instrumentSerialNumber);
							h("#Sono").val(data.data[0].factorySo);
							h("#CustName").val(data.data[0].customerName);
							//客户名
							khInfo["CustName"] = emptyStr(data.data[0].customerName); //参数赋值
							//邮编
							khInfo["postcode"] = emptyStr(data.data[0].postcode);
							//联系人
							khInfo["contactor"] = emptyStr(data.data[0].contact);
							//电话
							khInfo["telephone"] = emptyStr(data.data[0].telephone);
							//手机
							khInfo["Mobile"] = emptyStr(data.data[0].mobile);
							//省
							khInfo["Province"] = emptyStr(data.data[0].province);
							//市
							khInfo["City"] = emptyStr(data.data[0].city);
							//地址
							khInfo["shipaddress"] = emptyStr(data.data[0].homeAddress);
							//邮编
							khInfo["postCode"] = emptyStr(data.data[0].postCode);
							//省市区
							if (data.data[0].longitude && data.data[0].latitude) {
								getShengshiqv(data.data[0].longitude, data.data[0].latitude);
							} else {
								khInfo["shengShiQU"] = "";
							}
							
						}
					} else {
						app.toast(data.msg)
					}
				}, function(errorMsg) {
					app.closeWaiting()
					app.toast(errorMsg)
				});
			}
			
			function checkTodayIsOnjobInfo() {
				ajaxGetJson(BASE_URL + 'cc/spareParts/checkTodayIsOnjobInfo', {
				}, function(data) {
					if (data) {
						var dataObj = JSON.parse(data);
						if (dataObj.status) {//返回成功
						h("#Emergency_1").removeAttr("disabled");
							if (dataObj.record[0].IsOnjob == 1) {
								// 紧急时段
								h("#Emergency_1").removeAttr("disabled");
							} else {
								// 非紧急时段
								h("#Emergency_1").attr("disabled", "disabled");
							}
						}
					}
				});
			}
			// 获取详情的方法
			function getDetails(){
				app.showWaiting('加载中...')
				ajaxGet(BASE_URL + "cc/notice/getMyServiceNoticeDetail", {
					"ServiceNoticeId": ServiceNoticeId,
					"EnginnerId": app.getUser().enginnerId
				}, function(data) {
					loadingNum++;
					if(loadingNum >= loadingNo){
						app.closeWaiting()
					}
					console.log('加载完成==================================================================================================')
					if (data.code == 200) {
						khInfo.isWarranty = data.data[0].isWarranty
					}else{
						app.toast(data.msg)
					}
				}, function(errorMsg) {
					app.toast(errorMsg)
				});
			}
			
		</script>
		<!-- js代码 end -->

	</body>

</html>
